package org.jetlinks.pro.rule.engine.service;

import lombok.AllArgsConstructor;
import org.jetlinks.pro.rule.engine.entity.RuleInstanceEntity;
import org.jetlinks.pro.rule.engine.enums.RuleInstanceState;
import org.jetlinks.rule.engine.api.model.RuleEngineModelParser;
import org.jetlinks.rule.engine.cluster.RuleInstance;
import org.jetlinks.rule.engine.cluster.RuleInstanceRepository;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;

import javax.annotation.Nonnull;

@Component
@AllArgsConstructor
public class LocalRuleInstanceRepository implements RuleInstanceRepository {
    private final RuleInstanceService instanceService;

    private final RuleEngineModelParser parser;

    @Nonnull
    @Override
    public Flux<RuleInstance> findAll() {
        return instanceService
            .createQuery()
            .where(RuleInstanceEntity::getState, RuleInstanceState.started)
            .fetch()
            .map(en -> en.toRuleInstance(parser))
            ;
    }

    @Nonnull
    @Override
    public Flux<RuleInstance> findById(String id) {
        return instanceService
            .createQuery()
            .where(RuleInstanceEntity::getId, id)
            .and(RuleInstanceEntity::getState, RuleInstanceState.started)
            .fetch()
            .map(en -> en.toRuleInstance(parser))
            ;
    }
}
